package com.etlmaster.transformer.funcs;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.trans.core.Line;
import com.etlmaster.executor.trans.core.LineTransProcessor;
import com.etlmaster.executor.utils.LogWriter;

/**
 * 求时间差
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
@StepInstruction("timeDiff")
public class TransFieldTimeDiff  extends LineTransProcessor{
	private String sourceTimeIndex;
	private String targetTimeIndex;
	private String timeUnit;
	private String sourceTimeFormat;
	private String targetTimeFormat;
	public TransFieldTimeDiff(String sourceTab,String sourceCol,String targetTab,String targetCol,String changeCode,Map paramStr,Map var){
		
		super( sourceTab,sourceCol,targetTab,targetCol,changeCode, paramStr,var);
	
	}

	@Override
	public void transField(Line line) {
		
		SimpleDateFormat sourceformat=new SimpleDateFormat(sourceTimeFormat);
		SimpleDateFormat targetformat=new SimpleDateFormat(targetTimeFormat);
		try {
			String sourceTime=line.getField(line.getMeta().getColPosition(this.getSourceTab()+"_"+sourceTimeIndex.toUpperCase()));
			String targetTime=line.getField(line.getMeta().getColPosition(this.getSourceTab()+"_"+targetTimeIndex.toUpperCase()));
			Date sourceDate;
			if(sourceTime==null||sourceTime.trim().length()==0||sourceTime.equals("null"))
			{
				sourceDate=new Date();
			}else{
				sourceDate=sourceformat.parse(sourceTime);
			}
			Date targetDate=targetformat.parse(targetTime);
			long time=sourceDate.getTime()-targetDate.getTime();
			int rtnValue=0;
			switch(timeUnit){
				case "hour":
					rtnValue=(int) Math.ceil(time/(1000*60*60));
					break;
				case "day":
					rtnValue=(int) Math.ceil(time/(1000*60*60*24));
					break;
				default :
					rtnValue=(int) (Math.ceil(time/1000));
			}
			line.addField(rtnValue+"",this.getSourceTab(),this.getSourceCol()+"_1");
		} catch (ParseException e) {
			line.setSkip(true);
			LogWriter.addLog("ERROR","行级处理失败.{}",e.getMessage());
		}
		
	}

}
